new Vue({
    el: '#app',
    data() {
        return {
            fileList: [],
            tableData: [],
            form: {
                page: 1,
                limit: 15,
            },
            loading: false,
            success: 0,
            error: 0,
            logistics: [],//物流公司
        }
    },
    mixins:[importMixin],
    mounted() {
        this.getData();
    },
    methods: {
        getData() {
            const that = this;
            this.loading = true;
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryByTableName`,
                type: 'POST',
                data: {
                    Data: 'business_logistics_info',
                    Condition: "Row_Status <> '1'",
                },
                success: function (res) {
                    that.logistics = res;
                },
                complete: function (XMLHttpRequest) {
                    that.loading = false
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
            
        },
        submitUpload(i = 0) {
            const that = this;
            if (i < this.tableData.length) {
                this.loading = true;
                if (this.tableData[i].isError) {//异常数据
                    this.error++;
                    this.submitUpload(i + 1);
                } else if(this.tableData[i].Refund_Type&&this.tableData[i].Refund_Type.charAt(1) != '2'){
                    this.tableData[i].isStatus = '2';
                    this.tableData[i].Cause = '当前订单为退货中或已退款订单';
                    this.error++;
                    this.submitUpload(i + 1);
                } else if (!(!isNaN(parseFloat(this.tableData[i].Delivery_Quantity)) && isFinite(this.tableData[i].Delivery_Quantity))) {
                    this.tableData[i].isStatus = '2';
                    this.tableData[i].Cause = '发货数量不是一个数字';
                    this.error++;
                    this.submitUpload(i + 1);
                } else if (parseInt(this.tableData[i].Delivery_Quantity) == 0) {
                    this.tableData[i].isStatus = '2';
                    this.tableData[i].Cause = '发货数量不能为0';
                    this.error++;
                    this.submitUpload(i + 1);
                } else if (parseInt(this.tableData[i].Delivery_Quantity) > parseInt(this.tableData[i].Remain_Quantity)) {
                    this.tableData[i].isStatus = '2';
                    this.tableData[i].Cause = '发货数量不能大于剩余待货数量';
                    this.error++;
                    this.submitUpload(i + 1);
                } else { //校验通过
                    $.ajax({//查询信息
                        headers: requestHeaders(),
                        url: `${BASE_URL2}/member/getMemberPoint`,
                        type: 'POST',
                        data: {
                            Data: JSON.stringify([{
                                tableName: 'business_sales_order',
                                Condition: window.btoa(unescape(encodeURIComponent("Sales_Order_SerialNumber='" + that.tableData[i].Sales_Order_SerialNumber + "'"))),
                            }, {
                                tableName: 'business_sales_order_detail',
                                Condition: window.btoa(unescape(encodeURIComponent("Sales_Order_Detail_SerialNumber='" + that.tableData[i].Sales_Order_Detail_SerialNumber + "'"))),
                            }]),
                        },
                        success: function ({business_sales_order , business_sales_order_detail}) {
                            if (business_sales_order.length == 1 && business_sales_order_detail.length == 1) {
                                let Status = business_sales_order[0].Row_Status.charAt(0);
                                if (parseInt(that.tableData[i].Quantity) == parseInt(that.tableData[i].Delivery_Quantity1) + parseInt(that.tableData[i].Delivery_Quantity)) {
                                    business_sales_order[0].Row_Status = Status + '4'//发货中
                                    business_sales_order_detail[0].Row_Status = '2'//明细发货但没完成
                                } else {
                                    business_sales_order_detail[0].Row_Status = '1'//明细发货完成
                                }

                                let obj = {
                                    Sales_Order_Logistics_SerialNumber: '',
                                    Sales_Order_Detail_SerialNumber: that.tableData[i].Sales_Order_Detail_SerialNumber,
                                    Logistics_Number: that.tableData[i].Logistics_Number,
                                    Logistics_Code: that.tableData[i].Logistics_Code,
                                    Delivery_Quantity: that.tableData[i].Delivery_Quantity,
                                    Delivery_Data: getYMDHMSDate(),
                                }

                                let data = {
                                    Data: JSON.stringify({
                                        Add: { business_sales_order_logistics: [obj], base_operation_log: [generateLog('发货(批量)', '平台端操作', 'business_sales_order', JSON.stringify({ Modify: { business_sales_order, business_sales_order_detail }, Add: { business_sales_order_logistics: [obj] } }))]},
                                        Modify: { business_sales_order, business_sales_order_detail }
                                    })
                                };

                                that.submitForm(data, (res) => {//提交
                                    if (res.Status == 'success') {
                                         //订阅快递100
                                         $.ajax({
                                            headers: requestHeaders(),
                                            url: `${BASE_URL2}/waybill/subscribeWayBillState?Data=${that.tableData[i].Logistics_Number}`,
                                            type: 'GET',
                                            success: function (res) {
                                                that.tableData[i].Remain_Quantity = parseInt(that.tableData[i].Remain_Quantity) - parseInt(that.tableData[i].Delivery_Quantity),
                                                that.tableData[i].isStatus = '1';
                                                that.tableData[i].Cause = '',
                                                that.success++;
                                            },
                                            complete: function (XMLHttpRequest) {
                                                requestPretreatment(XMLHttpRequest);
                                            },
                                            dataType: "json"
                                        })
                                    } else {
                                        that.tableData[i].isStatus = '2';
                                        that.tableData[i].Cause = '未知错误'
                                        that.error++;
                                        that.submitUpload(i + 1);
                                    }
                                    
                                })
                            }else{
                                that.tableData[i].isStatus = '2';
                                that.tableData[i].Cause = '未查询到销售订单或明细'
                                that.error++;
                                that.submitUpload(i + 1);
                            }
                        },
                        complete: function (XMLHttpRequest) {
                            requestPretreatment(XMLHttpRequest);//config/config.js 响应预检
                        },
                        dataType: "json"
                    });
                }
            } else if (i != 0) {
                this.loading = false;
                this.$message.success("批量导入结束")
            } else {
                this.$message({
                    message: '请先导入模板后再上传',
                    type: 'warning'
                })
            }
        },
        submitForm(data, callback) {
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalSave`,
                type: 'POST',
                data,
                success: function (res) {
                    callback(res)
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            })
        },
        handleChange({ raw }) {//导入监听文件
            const that = this;
            var reader = new FileReader();
            reader.readAsBinaryString(raw);
            reader.onload = function (e) {
                var data = e.target.result;
                var wb = XLSX.read(data, {
                    type: 'binary' //以二进制的方式读取
                });
                var sheet = wb.Sheets[wb.SheetNames[0]];//sheet0代表excel表格中的第一页
                var json = XLSX.utils.sheet_to_json(sheet);//利用接口实现转换。
                //1.查询用户信息，并展示到页面上
                let sql1 = "";
                let business_sales_order_detail = [];
                json.forEach((item, index) => {
                    if (!business_sales_order_detail.some(i => i == (item['销售订单明细编码'] + '').trim())) {
                        business_sales_order_detail.push((item['销售订单明细编码'] + '').trim());
                        if (index == 0) {
                            sql1 = sql1 + "business_sales_order_detail.Sales_Order_Detail_SerialNumber='" + (item['销售订单明细编码'] + '').trim() + "'\r\n"
                        } else {
                            sql1 = sql1 + " or business_sales_order_detail.Sales_Order_Detail_SerialNumber='" + (item['销售订单明细编码'] + '').trim() + "'\r\n"
                        }
                    }
                })
                $.ajax({
                    headers: requestHeaders(),
                    type: 'POST',
                    url: `${BASE_URL2}/generalBusiness/generalQueryBySQLSerialNumber`,
                    data: {
                        SQLSerialNumber: 'A_business_sales_order_detail2',
                        Condition: '',
                        ExtensionCondition: window.btoa(unescape(encodeURIComponent(`and (${sql1})`))),
                    },
                    success: function (Result) {
                        let arr = [];
                        json.forEach(item => {
                            if (!Result.some(i => i.Sales_Order_Detail_SerialNumber == (item['销售订单明细编码'] + '').trim())) {
                                arr.push({
                                    Sales_Order_Logistics_SerialNumber:'',
                                    Sales_Order_Detail_SerialNumber: (item['销售订单明细编码'] + '').trim(),
                                    Logistics_Number: (item['物流编码'] + '').trim(),
                                    Logistics_Code: (item['物流公司编码'] + '').trim(),
                                    Delivery_Data: "",
                                    Delivery_Quantity:(item['发货数量'] + '').trim(),
                                    isError: true,
                                    isStatus: '2',
                                    Cause: '未查询到对应销售订单明细',
                                })
                            } else if (!that.logistics.some(i => i.Logistics_Name == (item['物流公司'] + '').trim())) {
                                arr.push({
                                    Sales_Order_Logistics_SerialNumber:'',
                                    Sales_Order_Detail_SerialNumber: (item['销售订单明细编码'] + '').trim(),
                                    Logistics_Number: (item['物流编码'] + '').trim(),
                                    Logistics_Code: (item['物流公司编码'] + '').trim(),
                                    Delivery_Data: "",
                                    Delivery_Quantity:(item['发货数量'] + '').trim(),
                                    isError: true,
                                    isStatus: '2',
                                    Cause: '未查询到对应物流公司',
                                })
                            } else if (arr.some(i => i.Sales_Order_Detail_SerialNumber == (item['销售订单明细编码'] + '').trim())) {
                                arr.push({
                                    Sales_Order_Logistics_SerialNumber:'',
                                    Sales_Order_Detail_SerialNumber: (item['销售订单明细编码'] + '').trim(),
                                    Logistics_Number: (item['物流编码'] + '').trim(),
                                    Logistics_Code: (item['物流公司编码'] + '').trim(),
                                    Delivery_Data: "",
                                    Delivery_Quantity:(item['发货数量'] + '').trim(),
                                    isError: true,
                                    isStatus: '2',
                                    Cause: '本次导入该订单已存在',
                                })
                            } else {
                                arr.push({
                                    ...Result.filter(i => i.Sales_Order_Detail_SerialNumber == (item['销售订单明细编码'] + '').trim())[0],
                                    Logistics_Name: (item['物流公司'] + '').trim(),
                                    Logistics_Number: (item['物流编码'] + '').trim(),
                                    Logistics_Code: that.logistics.filter(i => i.Logistics_Name == (item['物流公司'] + '').trim())[0].Logistics_Code,
                                    Delivery_Data: "",
                                    Delivery_Quantity:(item['发货数量'] + '').trim(),
                                    isEdit: false,
                                    isStatus: '0',
                                    Cause: '',
                                })
                            }
                        })
                        that.tableData = arr;
                    },
                    complete: function (XMLHttpRequest) {
                        requestPretreatment(XMLHttpRequest);
                    },
                    dataType: "json"
                });
            }
        },
        handleSizeChange(val) {
            this.form.page = 1;
            this.form.limit = val;
        },
        handleCurrentChange(val) {
            this.form.page = val;
        },
        handleEdit(row) {//修改当前行
            row.isEdit = !row.isEdit
        },
        handleRemove(index) {//移除当前行
            this.$confirm('是否要删除此行?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                this.tableData = this.tableData.filter((i, id) => id != (this.form.page - 1) * this.form.limit + index);
            }).catch(() => { });
        },
        handleClean() {//清空
            this.$confirm('是否要清空导入数据?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                this.tableData = []
            }).catch(() => { });
        },
    },
})